package com.code.test.dance;

import java.util.Arrays;

/**
 * 差分数组
 */
public class Chafen {

    public static void main(String[] args) {
        int[] origin = {10, 3, 6, 9, 2, 5, 0, 4};
        int[] cha = buildChafen(origin);
        System.out.println(Arrays.toString(cha));

        //还原会原来的数组
        int[] restore = restorChafen(cha);
        System.out.println(Arrays.toString(restore));
    }

    /**
     * 第i个元素 = 当前个- （i-1）个
     */
    public static int[] buildChafen(int[] nums) {
        int[] ret = new int[nums.length];
        ret[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {

            ret[i] = nums[i] - nums[i - 1];
        }
        return ret;
    }

    /**
     *  差分：第i个元素 = 当前个- （i-1）个
     *  还原：第i个元素 = 当前个 + (i-1)
     */
    public static int[] restorChafen(int[] nums) {
        int[] ret = new int[nums.length];
        for (int i = 1; i < nums.length; i++) {
            nums[i] += nums[i - 1];
        }
        return nums;
    }
}
